package com.ourteam.system.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.ourteam.system.dao.SysUser;
import com.ourteam.system.dao.SysUserDAOQueryBean;
import com.ourteam.system.dao.SysUserLoginLogDAOQueryBean;
import com.ourteam.system.dao.SysUserPhoto;
import com.ourteam.system.dao.SysUserPhotoDAOQueryBean;
import com.ourteam.system.dao.SysUserRoleRelate;
import com.ourteam.system.dao.SysUserRoleRelateDAOQueryBean;
import com.ourteam.system.dao.SysUserSetting;
import com.ourteam.system.dao.SysUserSettingDAOQueryBean;
import com.ourteam.system.domain.SysUserLoginLogBean;
import com.ourteam.system.domain.SysUserPhotoBean;
import com.ourteam.system.domain.SystemEventLogBean;
import com.ourteam.system.domain.SystemUser;
import com.ourteam.system.domain.SystemUserPassword;
import com.ourteam.system.domain.SystemUserRoleRelate;
import com.ourteam.system.domain.SystemUserStatusEnum;

/**
 * ϵͳ�û����� impl Generated Date 2009-09-14 17:23:29
 * 
 * @author $Auto Gen
 */
public class SysUserServiceImpl extends AbstractSysUserService {

	/**
	 * ����ϵͳ�û� impl
	 * 
	 * @param systemUser
	 * 
	 * @param aTransaction
	 * @param aContext
	 * @throws Exception
	 */
	@Override
	protected void doCreateSysUser(final com.ourteam.system.domain.SystemUser systemUser) throws Exception {

		SysUser sysUser = systemUser.convertToSysUser();

		if (sysUserDao.checkIsUnique(sysUser) == false) {
			throw new Exception("帐号 [" + sysUser.getUserAccount() + "," + sysUser.getUserName() + "] 已经存在");
		}

		sysUser.setPassword(DigestUtils.md5Hex("123456"));

		if (StringUtils.isEmpty(sysUser.getStatus())) {
			sysUser.setStatus(SystemUserStatusEnum.FREE.getName());
		}

		sysUserDao.insert(sysUser);

		long[] roleIds = this.sysRoleService.getDefaultSysRoleIds();

		SystemUserRoleRelate[] userRoleRelates = new SystemUserRoleRelate[roleIds.length];

		for (int i = 0; i < userRoleRelates.length; i++) {
			userRoleRelates[i] = new SystemUserRoleRelate();
			userRoleRelates[i].setRoleId(roleIds[i]);
			userRoleRelates[i].setUserId(sysUser.getId());
		}

		setSysUserAuthorities(sysUser.getId(), userRoleRelates);

		SystemEventLogBean systemEventLog = new SystemEventLogBean();

		systemEventLog.setEventOperatorId(sysUser.getOperatorId());
		systemEventLog.setEventData(JSON.toJSONString(sysUser, true));
		systemEventLog.setEventSource("sysUser");
		Map<String, String> eventContent = new HashMap<String, String>();

		eventContent.put("dataType", "系统用户");
		eventContent.put("dataDesc", sysUser.getUserName());

		this.systemEventLogService.addSystemEventLog("ADD_NEW_DATA", systemEventLog, eventContent);

	}

	/**
	 * �޸�ϵͳ�û� impl
	 * 
	 * @param systemUser
	 * 
	 * @param aTransaction
	 * @param aContext
	 * @throws Exception
	 */
	@Override
	protected void doModifySysUser(final com.ourteam.system.domain.SystemUser systemUser) throws Exception {
		SysUser sysUser = systemUser.convertToSysUser();

		if (sysUserDao.checkIsUnique(sysUser) == false) {
			throw new Exception("Account [" + sysUser.getUserAccount() + "] Is In Use");
		}

		sysUserDao.update(sysUser);

		SystemEventLogBean systemEventLog = new SystemEventLogBean();

		systemEventLog.setEventOperatorId(sysUser.getOperatorId());
		systemEventLog.setEventData(JSON.toJSONString(sysUser, true));
		systemEventLog.setEventSource("sysUser");
		Map<String, String> eventContent = new HashMap<String, String>();

		eventContent.put("dataType", "系统用户");
		eventContent.put("dataDesc", sysUser.getUserName());

	}

	@Override
	protected int doGetSysUserCount(SysUserDAOQueryBean aQueryBean) throws Exception {
		return sysUserDao.queryCount(aQueryBean);
	}

	@Override
	protected SystemUser[] doGetSysUsers(SysUserDAOQueryBean aQueryBean) throws Exception {
		SysUser[] sysUsers = sysUserDao.query(aQueryBean);

		return SystemUser.toArray(sysUsers);
	}

	@Override
	protected void doChangeUserPassword(SystemUserPassword aSystemUserPassword) throws Exception {

		SystemUser systemUser = getSysUserByAccount(aSystemUserPassword.getAccount());

		if (systemUser == null) {
			throw new Exception("Account [" + aSystemUserPassword.getAccount() + "] Not Found");
		}

		String password = DigestUtils.md5Hex(aSystemUserPassword.getPassword());

		SysUser sysUser = sysUserDao.findById(systemUser.getId());

		sysUser.setPassword(password);

		sysUserDao.update(sysUser);

	}

	@Override
	protected SystemUser doGetSysUserByAccount(String aAccount) throws Exception {

		SysUserDAOQueryBean queryBean = new SysUserDAOQueryBean();

		queryBean.createCriteria().andUserAccountEqualTo(aAccount);

		SysUser[] sysUsers = sysUserDao.query(queryBean);

		if (ArrayUtils.isEmpty(sysUsers)) {
			return null;

		} else {
			return new SystemUser(sysUsers[0]);
		}

	}

	@Override
	protected SystemUser doGetSysUserById(long aSystemUserId) throws Exception {
		SysUser sysUser = sysUserDao.findById(aSystemUserId);
		if (sysUser == null) {
			return null;
		} else {
			return new SystemUser(sysUser);
		}

	}

	@Override
	protected SystemUserPassword doGetSysUserPassword(String aAccount) throws Exception {

		SysUserDAOQueryBean queryBean = new SysUserDAOQueryBean();

		queryBean.createCriteria().andUserAccountEqualTo(aAccount);

		SystemUser systemUser = getSysUserByAccount(aAccount);

		if (systemUser == null) {
			return null;
		} else {
			SystemUserPassword userPassword = new SystemUserPassword();
			userPassword.setAccount(systemUser.getAccount());
			userPassword.setPassword(systemUser.getPassword());
			return userPassword;
		}

	}

	@Override
	protected SystemUserRoleRelate[] doGetSysUserAuthorities(long aSysUserId) throws Exception {

		SysUserDAOQueryBean queryBean = new SysUserDAOQueryBean();

		queryBean.createCriteria().andIdEqualTo(Long.valueOf(aSysUserId));

		SysUserRoleRelate[] userAuthorities = sysUserDao.querySysUserRoleRelate(queryBean);

		return SystemUserRoleRelate.toArray(userAuthorities);
	}

	@Override
	protected void doSetSysUserAuthorities(long aSysUserId, SystemUserRoleRelate[] aSystemUserAuthorities)
			throws Exception {

		if (aSystemUserAuthorities == null) {
			aSystemUserAuthorities = new SystemUserRoleRelate[0];
		}

		SysUser sysUser = sysUserDao.findById(aSysUserId);

		if (sysUser == null) {
			throw new Exception("Sys User ID [" + aSysUserId + "] Not Found");
		}

		SysUserRoleRelate[] userAuthorities = new SysUserRoleRelate[aSystemUserAuthorities.length];

		for (int i = 0; i < userAuthorities.length; i++) {
			userAuthorities[i] = aSystemUserAuthorities[i].convertToSysUserRoleRelate();

		}

		SysUserRoleRelateDAOQueryBean queryBean = new SysUserRoleRelateDAOQueryBean();

		queryBean.createCriteria().andUserIdEqualTo(aSysUserId);

		sysUserRoleRelateDao.synchronize(userAuthorities, queryBean);

		SysUserRoleRelate[] roleRelates = sysUserRoleRelateDao.query(queryBean);

		List<String> userRoles = new ArrayList<>();

		for (int i = 0; i < roleRelates.length; i++) {
			SysUserRoleRelate sysUserRoleRelate = roleRelates[i];
			userRoles.add(sysUserRoleRelate.getRoleName());
		}

		sysUser.setUserRole(StringUtils.join(userRoles, ","));

		sysUserDao.update(sysUser);

	}

	@Override
	protected void doDeleteSysUsers(long[] sysUserIds, long operatorId) throws Exception {

		SysUserDAOQueryBean sysUserDAOQueryBean = new SysUserDAOQueryBean();

		sysUserDAOQueryBean.createCriteria().andIdIn(sysUserIds);

		SysUser[] sysUsers = this.sysUserDao.query(sysUserDAOQueryBean);

		for (int i = 0; i < sysUsers.length; i++) {

			SysUser sysUser = sysUsers[i];

			SystemEventLogBean systemEventLog = new SystemEventLogBean();

			systemEventLog.setEventOperatorId(operatorId);

			systemEventLog.setEventSource("sysUser");
			Map<String, String> eventContent = new HashMap<String, String>();

			eventContent.put("dataType", "系统用户");
			eventContent.put("dataDesc", sysUser.getUserName());

			this.systemEventLogService.addSystemEventLog("DELETE_DATA", systemEventLog, eventContent);

		}

		this.sysUserDao.delete(sysUserDAOQueryBean);
	}

	@Override
	protected SystemUser[] doGetSysUsersByIds(long[] sysUserId) throws Exception {

		SysUserDAOQueryBean sysUserDAOQueryBean = new SysUserDAOQueryBean();

		sysUserDAOQueryBean.createCriteria().andIdIn(sysUserId);

		return SystemUser.toArray(this.sysUserDao.query(sysUserDAOQueryBean));
	}

	@Override
	protected void doResetSysUserPassword(long sysUserId, String aPassword) throws Exception {

		SysUser sysUser = this.sysUserDao.findById(sysUserId);

		if (sysUser == null) {
			throw new Exception("User Not Found");
		}

		if (StringUtils.isEmpty(aPassword)) {
			aPassword = "user";
		}

		String password = DigestUtils.md5Hex(aPassword);

		sysUser.setPassword(password);

		sysUserDao.update(sysUser);
	}

	@Override
	protected void doAddSysUserLoginLog(SysUserLoginLogBean sysUserLoginLogBean) throws Exception {

		this.sysUserLoginLogDao.insert(sysUserLoginLogBean.convertToSysUserLoginLog());

	}

	@Override
	protected void doModifySysUserLoginLog(SysUserLoginLogBean sysUserLoginLogBean) throws Exception {

		this.sysUserLoginLogDao.update(sysUserLoginLogBean.convertToSysUserLoginLog());

	}

	@Override
	protected SysUserLoginLogBean doGetSysUserLoginLogBySessionId(long userId, String sessionId) throws Exception {

		SysUserLoginLogDAOQueryBean queryBean = new SysUserLoginLogDAOQueryBean();

		queryBean.createCriteria().andUserIdEqualTo(userId).andSessionIdEqualTo(sessionId);

		SysUserLoginLogBean[] loginLogBeans = querySysUserLoginLog(queryBean);

		return ArrayUtils.isNotEmpty(loginLogBeans) ? loginLogBeans[0] : null;
	}

	@Override
	protected SysUserLoginLogBean[] doQuerySysUserLoginLog(SysUserLoginLogDAOQueryBean queryBean) throws Exception {

		return SysUserLoginLogBean.toArray(this.sysUserLoginLogDao.query(queryBean));
	}

	@Override
	protected int doQuerySysUserLoginLogCount(SysUserLoginLogDAOQueryBean queryBean) throws Exception {

		return this.sysUserLoginLogDao.queryCount(queryBean);
	}

	@Override
	protected void doSetUserSetting(long userId, String itemName, String value) throws Exception {

		SysUserSetting setting = new SysUserSetting();

		setting.setUserId(userId);

		setting.setItemName(itemName);

		setting.setItemValue(value);

		SysUserSettingDAOQueryBean queryBean = new SysUserSettingDAOQueryBean();

		queryBean.createCriteria().andUserIdEqualTo(userId).andItemNameEqualTo(itemName);

		this.sysUserSettingDao.synchronize(new SysUserSetting[] { setting }, queryBean);

	}

	@Override
	protected String doGetUserSetting(long userId, String itemName) throws Exception {

		SysUserSettingDAOQueryBean queryBean = new SysUserSettingDAOQueryBean();

		queryBean.createCriteria().andUserIdEqualTo(userId).andItemNameEqualTo(itemName);

		SysUserSetting[] settings = this.sysUserSettingDao.query(queryBean);

		return ArrayUtils.isNotEmpty(settings) ? settings[0].getItemValue() : null;
	}

	@Override
	protected void doSetUserPhoto(SysUserPhotoBean userPhoto) throws Exception {
		SysUserPhotoDAOQueryBean queryBean = new SysUserPhotoDAOQueryBean();

		queryBean.createCriteria().andUserIdEqualTo(userPhoto.getUserId());

		SysUserPhoto[] userPhotos = this.sysUserPhotoDao.query(queryBean);

		if (ArrayUtils.isEmpty(userPhotos)) {
			this.sysUserPhotoDao.insert(userPhoto.convertTo());
		} else {
			userPhotos[0].setUserPhoto(userPhoto.getUserPhoto());
			this.sysUserPhotoDao.update(userPhotos[0]);
		}
	}

	@Override
	protected SysUserPhotoBean doGetUserPhoto(long userId) throws Exception {

		SysUserPhotoDAOQueryBean queryBean = new SysUserPhotoDAOQueryBean();

		queryBean.createCriteria().andUserIdEqualTo(userId);

		SysUserPhoto[] userPhotos = this.sysUserPhotoDao.query(queryBean);

		return new SysUserPhotoBean(userPhotos[0]);
	}

}
